import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import axios from 'axios'
export default defineStore('newList', () => {

    const oriList = ref([])

    const getList = async () => {
        const res = await axios.get('http://localhost:5173/list')
        console.log(res)
        oriList.value = res.data
    }

    const update = async (item) => {
        const res = await axios.patch('http://localhost:5173/edit/'+item.id, item)
        console.log(res)
        getList()
    }
    const del = async (id) => {
        const res = await axios.delete('http://localhost:5173/del/'+id)
        console.log(res)
        getList()
    }

    const add = async (data) => {
        const res = await axios.post('http://localhost:5173/add', data)
        console.log(res)
        getList()
    }
    const delDone = async () => {
        const res = await axios.delete('http://localhost:5173/deldone')
        getList()
    }

    const type = ref('all') // 'all' 'yes' 'no'

    const list = computed(()=> {
        if(type.value === 'all') {
            return oriList.value
        } else if(type.value === 'yes') {
            return oriList.value.filter(it => it.isDone)
        } else {
            return oriList.value.filter(it => !it.isDone)
        }
    })
    const leftCount = computed(()=> {
            return oriList.value.filter(it => !it.isDone).length
    })

    const setType = curType => type.value = curType


    return {type, list, oriList, getList,update,del, add,setType,delDone, leftCount }
}, {
    persist: {
        key: 'my-custom-key',
        paths: ['oriList'],
    }
})